<!--

*		
*	                  _________________________________________________________
*	                  |shi shi shi shi shi shi shi shi shi shi shi shi shi shi|
*	             /    |shi shi shi shi shi shi shi shi shi shi shi shi shi shi|
*	            /---, |shi shi shi shi shi shi shi shi shi shi shi shi shi shi|
*	       -----# ==| |shi shi shi shi shi shi shi shi shi shi shi shi shi shi|
*	       | :) # ==| |shi shi shi shi shi shi shi shi shi shi shi shi shi shi|
*	  -----'----#   | |_______________________________________________________|
*	  |)___()  '#   |______====____   \___________________________________|
*	 [_/,-,\"--"------ //,-,  ,-,\\\   |/             //,-,  ,-,  ,-,\\ __#
*	   ( 0 )|===******||( 0 )( 0 )||-  o              '( 0 )( 0 )( 0 )||
*	----'-'--------------'-'--'-'-----------------------'-'--'-'--'-'--------------

                              作者找了一辆卡车拉走了下边的`屎`
                              作者找了一辆卡车拉走了下边的`屎`
                              作者找了一辆卡车拉走了下边的`屎`

-->

<template>
  <el-form :model="form" ref="ruleFormRef" :rules="rules" :validate-on-rule-change="false" class="demo-ruleForm"
    status-icon label-width="100px">
    <el-form-item label="题目" prop="questionTitle">
      <el-input v-model="form.questionTitle" />
    </el-form-item>
    <el-form-item label="题目解析" prop="analysis">
      <el-input v-model="form.analysis" />
    </el-form-item>
    <el-form-item label="题目类型">
      <el-radio-group v-model="form.questionType" size="large" @change="typeChange(type)">
        <el-radio value="0">单选</el-radio>
        <el-radio value="1">多选</el-radio>
        <el-radio value="2">判断</el-radio>
        <el-radio value="3">主观题</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="排序">
      <el-input-number v-model="form.sort" :min="1" />
    </el-form-item>

    <!-- 单选或多选开始 -->
    <el-row v-for="(item, index) in form.options" :key="index" v-if="form.questionType == 0 || form.questionType == 1">
      <el-form-item label="选项标题" :prop="'options.' + index + '.optionTitle'">
        <el-input v-model="item.optionTitle" disabled style="width: 200px;" />
      </el-form-item>
      <el-form-item label="选项内容" style="margin-left: 20px;" :prop="'options.' + index + '.optionDescribe'">
        <el-input type="textarea" v-model="item.optionDescribe" :autosize="{ minRows: 1 }" style="width: 600px;" />
      </el-form-item>
      <el-form-item label="是否正确" style="margin-left: 20px;">
        <el-radio-group v-model="item.status" size="large">
          <el-radio :value="0">不是</el-radio>
          <el-radio :value="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-row>
    <!-- 单选或多选结束 -->

    <!-- 判断开始 -->
    <el-row v-for="(item, index) in form.options" :key="index" v-if="form.questionType == 2">
      <el-form-item label="选项标题" :prop="'options.' + index + '.optionTitle'">
        <el-input v-model="item.optionTitle" disabled style="width: 200px;" />
      </el-form-item>
      <el-form-item label="选项内容" style="margin-left: 20px;" :prop="'options.' + index + '.optionDescribe'">
        <el-input type="textarea" v-model="item.optionDescribe" disabled :autosize="{ minRows: 1 }"
          style="width: 600px;" />
      </el-form-item>
      <el-form-item label="是否正确" style="margin-left: 20px;">
        <el-radio-group v-model="item.status" size="large">
          <el-radio :value="0">不是</el-radio>
          <el-radio :value="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-row>
    <!-- 判断结束 -->

    <!-- 主观题开始 -->
    <el-form-item label="参考答案" style="margin-left: 20px;" v-if="form.questionType == 3"
      prop="options[0].optionDescribe">
      <el-input type="textarea" v-model="form.options[0].optionDescribe" :autosize="{ minRows: 1 }"
        style="width: 600px;" />
    </el-form-item>
    <!-- 主观题结束 -->

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import axios from '@/axios/index.js'
import { useStaffStore } from '@/stores/staff'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()//toure
const router = useRouter()//router
const ruleFormRef = ref()//规则
const form = ref({
  questionBanksId: route.params.questionBankId,
  questionTitle: '',
  analysis: '',
  questionType: '0',
  sort: 1,
  staffId: useStaffStore().staffInfo.staff.id,
  questionStatus: 0,
  number: 4,
  options: []
})//表单

let type = ref(form.value.questionType)//存放题目类型

const rules = ref({
  questionTitle: [
    { required: true, message: '请输入题目', trigger: 'blur' },
    { min: 10, max: 200, message: '题目名称长度必须在10-200字之间', trigger: 'change' },
  ],
  analysis: [
    { required: true, message: '请输入题目解析', trigger: 'blur' },
    { min: 1, max: 200, message: '题目解析长度必须在1-200字之间', trigger: 'change' },
  ],
  optionDescribe: [
    { required: true, message: '请输入参考答案', trigger: 'blur' },
    { min: 1, max: 200, message: '主观题内容长度必须在1-200字之间', trigger: 'change' }
  ]
})//规则

//添加
let save = function () {
  //发送了一个请求,参数是form.value的数据
  axios.post(`/api/v1/admin/questions`,
    form.value,
    {
      headers: {
        "content-type": "application/json"
      }
    }
  ).then(response => {
    //响应弹窗
    ElMessage({
      type: 'success',
      message: response.data.message
    })
    //跳转到题目管理页面
    router.push(`/questionBank/questions/${route.params.questionBankId}`)
  })
}

//修改
let update = function () {
  //发送了一个请求,参数是form.value的数据
  axios.put(`/api/v1/admin/questions`,
    form.value,
    {
      headers: {
        "content-type": "application/json"
      }
    }
  ).then(response => {
    //响应弹窗
    ElMessage({
      type: 'success',
      message: response.data.message
    })
    //跳转到题目管理页面
    router.push(`/questionBank/questions/${route.params.questionBankId}`)
  })
}

//确定按钮
const onSubmit = () => {
  //计算正确答案的个数
  let optionCount = ref(0)
  //循环遍历选项
  for (let i = 0; i < form.value.options.length; i++) {
    //如果选项的状态等于1的正确答案个数++
    if (form.value.options[i].status == 1) {
      optionCount.value++
    }
  }

  //判断正确选项是否合格
  switch (form.value.questionType) {
    case "0":
      //当题目类型为单选的时候判断正确答案选项数是否为1,如果不为1则提示
      if (optionCount.value != 1) {
        ElMessageBox.alert('请选择一项正确答案', '系统提示', {
          confirmButtonText: '确认',
        })
        return
      } else {
        break
      }
    case "1":
      //当题目类型为多选的时候判断正确答案选项数是是否不为0,如果为0则提示
      if (optionCount.value <= 1) {
        ElMessageBox.alert('请至少选择两项正确答案', '系统提示', {
          confirmButtonText: '确认',
        })
        return
      } else {
        break
      }
    case "2":
      //当题目类型为判断的时候判断正确答案选项数是否为1,如果不为1则提示
      if (optionCount.value != 1) {
        ElMessageBox.alert('请选择一项正确答案', '系统提示', {
          confirmButtonText: '确认',
        })
        return
      } else {
        break
      }
  }
  //题目审核状态恢复为未审批状态
  form.value.questionStatus = 0
  //如果题目id为0则是添加,否则是修改
  if (form.value.options[0].questionId == 0) {
    save()
  } else {
    update()
  }
}

//取消按钮
const cancel = function () {
  //直接回到题目管理页面
  router.push(`/questionBank/questions/${route.params.questionBankId}`)
}

onMounted(() => {
  //页面刚加载时获取路径的id,如果路径的id是0说明是添加,否则是修改
  if (route.params.id == 0) {
    //如果是添加,则循环遍历4个选项
    for (let i = 0; i < form.value.number; i++) {
      //给表单中添加四个选项
      form.value.options.push({
        questionId: route.params.id,
        optionTitle: String.fromCharCode(65 + i),
        optionDescribe: '',
        status: 0
      })
      //给选项标题添加规则
      rules.value[`options.${i}.optionTitle`] = [
        { required: true, message: '请输入选项标题', trigger: 'blur' },
        { min: 1, max: 5, message: '选项标题长度必须在1-200字之间', trigger: 'change' },
      ]
      //给选项内容添加规则
      rules.value[`options.${i}.optionDescribe`] = [
        { required: true, message: '请输入选项内容', trigger: 'blur' },
        { min: 1, max: 50, message: '选项内容长度必须在1-50字之间', trigger: 'change' },
      ]
    }
  } else {
    //如果是修改,则先查询单个题目
    axios.get(`/api/v1/admin/questions/id/${route.params.id}`).then(response => {
      //将题目数据存放到form.value中
      form.value = response.data.data
      //给form.value.number初始化为4,这个number是选项的个数
      form.value.number = 4
      //type存放的是题目的类型,用于下面撤回
      type.value = form.value.questionType
      //循环给选项标题和选项内容添加规则
      for (let i = 0; i < response.data.data.options.length; i++) {
        rules.value[`options.${i}.optionTitle`] = [
          { required: true, message: '请输入选项标题', trigger: 'blur' },
          { min: 1, max: 5, message: '选项标题长度必须在1-200字之间', trigger: 'change' },
        ]
        rules.value[`options.${i}.optionDescribe`] = [
          { required: true, message: '请输入选项内容', trigger: 'blur' },
          { min: 1, max: 50, message: '选项内容长度必须在1-50字之间', trigger: 'change' },
        ]
      }
    })
  }
  //清除表单一进入页面久有的的表单规则验证
  ruleFormRef.value.clearValidate()
})

//选项个数发生变化
let handleChange = function (value) {
  //备份表单的选项
  let backForm = form.value.options
  //存放新的表单的选项
  let tempForm = []

  //如果修改的选项个数为2说明是判断题,则选项直接写死对错
  if (value == 2) {
    tempForm.push({
      questionId: route.params.id,
      optionTitle: '对',
      optionDescribe: '对',
      status: 0
    })
    tempForm.push({
      questionId: route.params.id,
      optionTitle: '错',
      optionDescribe: '错',
      status: 0
    })
  } else {
    //否则就遍历选项个数
    for (let i = 0; i < value; i++) {
      //如果i大于等于备份的选项个数,说明添加的选项,往新表单的选项数组添加新选项
      if (i >= backForm.length) {
        tempForm.push({
          questionId: route.params.id,
          optionTitle: String.fromCharCode(65 + i),
          optionDescribe: '',
          status: 0
        })
      } else {
        //如果i小于备份的选项个数,则备份的选项放到新表单的选项数组
        tempForm.push({
          questionId: route.params.id,
          optionTitle: String.fromCharCode(65 + i),
          optionDescribe: backForm[i].optionDescribe,
          status: 0
        })
      }
      //给每个选项标题添加规则
      rules.value[`options.${i}.optionTitle`] = [
        { required: true, message: '请输入选项标题', trigger: 'blur' },
        { min: 1, max: 5, message: '选项标题长度必须在1-200字之间', trigger: 'change' },
      ]
      //给每个选项内容添加规则
      rules.value[`options.${i}.optionDescribe`] = [
        { required: true, message: '请输入选项内容', trigger: 'blur' },
        { min: 1, max: 50, message: '选项内容长度必须在1-50字之间', trigger: 'change' },
      ]
    }
  }
  //将选项赋值给form.value.options
  form.value.options = tempForm
}

//类型发生变化
let typeChange = function (questionType) {
  if (form.value.options[0].questionId == 0) {
    if (form.value.questionType == 2 || form.value.questionType == 3) {
      //如果点击了确认,将表单的选项类型赋值给type
      type.value = form.value.questionType
      //如果表单的选项类型为2,说明是判断题
      if (form.value.questionType == 2) {
        //把表单的number(选项个数)改为2
        form.value.number = 2
        //把渲染的选项个数改为2
        handleChange(2)
      }
    }
    //如果选项类型变成了单选或多选
    if (form.value.questionType == 0 || form.value.questionType == 1) {
      //将表单的类型赋值给type,方便撤回
      type.value = form.value.questionType
      //给表单的选项个数设置为4
      form.value.number = 4
      //渲染4个选项
      handleChange(4)
    }
    //如果选项类型变成了客观题
    if (form.value.questionType == 3) {
      //选项个数设置为0
      form.value.number = 0
      //不渲染选项
      handleChange(0)
      //表单选项数组添加一个选项
      form.value.options.push({
        questionId: route.params.id,
        optionTitle: '',
        optionDescribe: '',
        status: 0
      })
      //给选项设置规则
      rules.value[`options[0].optionDescribe`] = [
        { required: true, message: '请输入参考答案', trigger: 'blur' },
        { min: 1, max: 200, message: '参考答案长度必须在1-200字之间', trigger: 'change' },
      ]
    }
    return
  }
  //备份选项,方便撤回
  let backForm = form.value.options
  //如果选项类型从其他变成判断题或者客观题,则提示该操作将丢失剩余选项
  if (form.value.questionType == 2 || form.value.questionType == 3) {
    //提示信息
    ElMessageBox.confirm(
      '此操作将永久丢失后边两个选项,请确认是否继续',
      '系统提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      //如果点击了确认,将表单的选项类型赋值给type
      type.value = form.value.questionType
      //如果表单的选项类型为2,说明是判断题
      if (form.value.questionType == 2) {
        //把表单的number(选项个数)改为2
        form.value.number = 2
        //把渲染的选项个数改为2
        handleChange(2)
      }
    }).catch(() => {
      //如果点击了取消,把表单的选项类型恢复成之前的选项类型
      form.value.questionType = questionType
      //把选项内容撤回
      form.value.options = backForm
      return
    })
  }
  //如果选项类型变成了单选或多选
  if (form.value.questionType == 0 || form.value.questionType == 1) {
    //将表单的类型赋值给type,方便撤回
    type.value = form.value.questionType
    //给表单的选项个数设置为4
    form.value.number = 4
    //渲染4个选项
    handleChange(4)
  }
  //如果选项类型变成了客观题
  if (form.value.questionType == 3) {
    //选项个数设置为0
    form.value.number = 0
    //不渲染选项
    handleChange(0)
    //表单选项数组添加一个选项
    form.value.options.push({
      questionId: route.params.id,
      optionTitle: '',
      optionDescribe: '',
      status: 0
    })
    //给选项设置规则
    rules.value[`options[0].optionDescribe`] = [
      { required: true, message: '请输入参考答案', trigger: 'blur' },
      { min: 1, max: 200, message: '参考答案长度必须在1-200字之间', trigger: 'change' },
    ]
  }
}

//提交验证
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      onSubmit()
    }
  })
}
</script>

<style scoped>
.el-row {
  align-items: flex-start;
}
</style>
